package banner

import (
	"context"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/miniapp"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetBannerByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetBannerByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBannerByIdLogic {
	return &GetBannerByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetBannerByIdLogic) GetBannerById(req *types.IDReq) (resp *types.BannerInfoResp, err error) {
	data, err := l.svcCtx.BackendRpc.BackendGetBannerById(l.ctx, &backendclient.IDReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}

	var media []*types.MediaInfo
	if len(data.Media) > 0 {
		for _, v := range data.Media {
			var url *string
			if v.Url != nil {
				url = v.Url
			} else if v.Uri != nil {
				url = v.Uri
			}
			media = append(media, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Thumbnail: v.Thumbnail,
				Order:     v.Order,
				Url:       url,
				Name:      v.Name,
				MimeType:  v.MimeType,
				AltText:   v.AltText,
				MetaData:  v.MetaData,
			})
		}
	}

	option := utils.GetOptionByStatus(data.Status)
	var linkUrl *string
	var linkUrlInvalid bool
	if data.LinkType != nil && *data.LinkType == uint32(globalkey.SettingBannerLinkTypeAbsolute) { // H5 绝对路径
		linkUrl = data.LinkUrl
	} else {
		url := miniapp.GetLinkUrl(data.LinkType, data.AdType, data.AdId, data.LinkUrl)
		if len(url) > 0 {
			linkUrl = pointy.GetPointer(url)
		} else if data.LinkUrl != nil && len(*data.LinkUrl) > 0 {
			linkUrl = data.LinkUrl
			linkUrlInvalid = true
		}
	}

	return &types.BannerInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.BannerInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			PicUrl:         data.PicUrl,
			Type:           data.Type,
			Title:          data.Title,
			LinkType:       data.LinkType,
			LinkUrl:        linkUrl,
			LinkUrlInvalid: linkUrlInvalid,
			AdType:         data.AdType,
			AdId:           data.AdId,
			Status:         data.Status,
			Sort:           data.Sort,
			StartedAt:      data.StartedAt,
			EndedAt:        data.EndedAt,
			Media:          media,
		},
	}, nil
}
